﻿using System;
using System.Linq;
using System.Data;
using System.Globalization;
using System.Web.UI.WebControls;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.MODEL;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using Telerik.Web.UI;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Web.UI;
using KPIS.DBM;
using KPIS.GERP.GFMS.DAL;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_Payroll : System.Web.UI.Page
    {
        private Main main = new Main();
        private SsMng creatby = new SsMng();
        private IBLL_FIM_Payroll bll = new B_FIM_Payroll();
        private D_FIM_Payroll dal = new D_FIM_Payroll();
        private IBLL_BGM_ProjectOperationExpense poeBll = new B_BGM_ProjectOperationExpense();
        private IBLL_BGM_ProjectOperation popBll = new B_BGM_ProjectOperation();
        private IBLL_BGM_MAS_Source sourceBll = new B_BGM_MAS_Source();
        private B_FIM_MoneyRequests mrBll = new B_FIM_MoneyRequests();
        private B_FIM_MoneyRequestDtls mrdBll = new B_FIM_MoneyRequestDtls();
        private B_HRM_PS_EmployeeTypes empTypeBll = new B_HRM_PS_EmployeeTypes();
        private B_BGM_MAS_ExpenseGroup expGrpBll = new B_BGM_MAS_ExpenseGroup();
        IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();
        IBLL_FIM_Cheques cheque = new B_FIM_Cheques();
        IBLL_FIM_ChequeBooks cb = new B_FIM_ChequeBooks();
        IBLL_FIM_Payments payment = new B_FIM_Payments();
        IBLL_CodeGenerate cg = new B_CodeGenerate();
        IBLL_FIM_PaymentCheques paymentch = new B_FIM_PaymentCheques();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
        private enum EditorCommand{ViewAll,Insert,Update,AddNew,Edit,Detail,ViewAllDeduction,
            InsertDeduction,UpdateDeduction,AddNewDeduction,EditDeduction,DetailDeduction}

        #region Page Event

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
                InitialBind();
                UpdateUI(EditorCommand.ViewAll);
                InitialBindComplete();

                ddlBankAccSeq_SelectedIndexChanged(null, null);
                LoadDDLChequeSeq();
                LoadDDLBankAccSeq();
                lblSubmitSucess.Visible = false;
            }
        }

        protected void cmdViewAll_Click(object sender, EventArgs e)
        {
            hdfPayRollSeq.Value = null;
            hdfYearNo.Value = null;
            hdfMonthNo.Value = null;
            UpdateUI(EditorCommand.ViewAll);
            LoadLabelPayrollStatus();
            ClearControl();
            LoadRadGridIndex();
        }

        protected void cmdViewAllDeduction_Click(object sender, EventArgs e)
        {
            LoadRadGridDeductionIndex();
            UpdateUI(EditorCommand.Detail);
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            ClearControl();
            hdfYearNo.Value = txbYearNo.Text;
            hdfMonthNo.Value = ddlMonth.SelectedValue;
            txbBgmYearNo.Value = bll.GetCurrentBgmYear();
            UpdateUI(EditorCommand.AddNew);
            LoadDdlEmpTypeSeq();
            LoadlblMonthYear();
            LoadDdlProjOper();
            LoadDdlSource();
            LoadDdlMasContact();
            LoadDdlExpenseGroup(); 

            dtpReqDate.SetValue(DateTime.Now);
        }

        protected void cmdAddNewDeduction_Click(object sender, EventArgs e)
        {
            ClearControlDeduction();
            UpdateUI(EditorCommand.AddNewDeduction);
            LoadDdlMasContactDeduction();
            ddlConIdDeduction.SelectedValue = ddlConId.SelectedValue;
        }

        protected void cmdEdit_OnCommand(object sender, CommandEventArgs e)
        {
            ClearControl();
            hdfPayRollSeq.Value = Convert.ToString(e.CommandArgument); 
            if(string.IsNullOrEmpty(hdfPayRollSeq.Value))
            {
                main.MessageAlert2(Page, "กรุณาเลือกข้อมูล");
                return;
            }
            LoadEditor();
            //LoadDdlEmpTypeSeq();
            //LoadDdlProjOper(); 
            //LoadDdlSource();
            //LoadDdlMasContact();
            //LoadDdlExpenseGroup();
            //dtpReqDate.SetValue(DateTime.Now);
            UpdateUI(EditorCommand.Edit);
        }

        protected void cmdEditDeduction_OnCommand(object sender, CommandEventArgs e)
        {
            ClearControlDeduction();
            hdfPayRollDeductionSeq.Value = Convert.ToString(e.CommandArgument); 
            if(string.IsNullOrEmpty(hdfPayRollDeductionSeq.Value))
            {
                main.MessageAlert2(Page, "กรุณาเลือกข้อมูล");
                return;
            }
            LoadEditorDeduction();
            //LoadDdlEmpTypeSeq();
            //LoadDdlProjOper(); 
            //LoadDdlSource();
            //LoadDdlMasContact();
            //LoadDdlExpenseGroup();
            //dtpReqDate.SetValue(DateTime.Now);
            UpdateUI(EditorCommand.EditDeduction);
        }
        
        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            if (!Insert()) return;
            LoadRadGridIndex();
            UpdateUI(EditorCommand.Insert);
            LoadRadGridDeductionIndex();
        }
        
        protected void cmdInsertDeduction_Click(object sender, EventArgs e)
        {
            if (!InsertDeduction()) return;
            LoadRadGridDeductionIndex();
            UpdateUI(EditorCommand.InsertDeduction);
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            if (!Update()) return;
            LoadRadGridIndex();
            UpdateUI(EditorCommand.Update);
            LoadRadGridDeductionIndex();
        }

        protected void cmdUpdateDeduction_Click(object sender, EventArgs e)
        {
            if (!UpdateDeduction()) return;
            LoadRadGridDeductionIndex();
            UpdateUI(EditorCommand.UpdateDeduction);
        }
        
        protected void cmdDetail_OnCommand(object sender, CommandEventArgs e)
        {
            try
            {
                hdfPayRollSeq.Value = Convert.ToString(e.CommandArgument);
                if (string.IsNullOrEmpty(hdfPayRollSeq.Value))
                {
                    main.MessageAlert2(Page, "กรุณาเลือกข้อมูล");
                    return;
                }
                LoadEditor();
                //var payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value);
                //var payroll = bll.GetPayrolls(payroll_seq).First();
                //txbBgmYearNo.Value = payroll.bgm_year_no;
                //LoadDdlProjOper();
                //LoadDdlSource();
                //LoadDdlMasContact();
                //LoadDdlExpenseGroup();
                //dtpReqDate.SetValue(DateTime.Now);
                LoadRadGridDeductionIndex();
                UpdateUI(EditorCommand.Detail);
            } catch (Exception ex)
            {
                    main.MessageAlert2(Page, ex.Message);
            }
        }
        
        protected void cmdDetailDeduction_OnCommand(object sender, CommandEventArgs e)
        {
            hdfPayRollDeductionSeq.Value = Convert.ToString(e.CommandArgument); 
            if(string.IsNullOrEmpty(hdfPayRollDeductionSeq.Value))
            {
                main.MessageAlert2(Page, "กรุณาเลือกข้อมูล");
                return;
            }
            //LoadEditor();
            //var payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value);
            //var payroll = bll.GetPayrolls(payroll_seq).First();
            //txbBgmYearNo.Value = payroll.bgm_year_no;
            //LoadDdlProjOper();
            //LoadDdlSource();
            //LoadDdlMasContact();
            //LoadDdlExpenseGroup();
            //dtpReqDate.SetValue(DateTime.Now);
            LoadRadGridDeductionIndex();
            UpdateUI(EditorCommand.DetailDeduction);
        }

        protected void cmdDelete_OnCommand(object sender, CommandEventArgs e)
        {
            hdfPayRollSeq.Value = Convert.ToString(e.CommandArgument); 
            if (string.IsNullOrEmpty(hdfPayRollSeq.Value)) 
            {
                main.MessageAlert2(Page, "กรุณาเลือกข้อมูล");
                return;
            }
            var payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value);
            bll.DeletePayroll(payroll_seq, Convert.ToInt32(Session["EmpSeq"]));
            hdfPayRollSeq.Value = null;
            LoadRadGridIndex();
            UpdateUI(EditorCommand.ViewAll);
        }

        protected void cmdDeleteDeduction_OnCommand(object sender, CommandEventArgs e)
        {
            hdfPayRollDeductionSeq.Value = Convert.ToString(e.CommandArgument); 
            if (string.IsNullOrEmpty(hdfPayRollDeductionSeq.Value)) 
            {
                main.MessageAlert2(Page, "กรุณาเลือกข้อมูล");
                return;
            }
            var payroll_deduction_seq = Convert.ToInt32(hdfPayRollDeductionSeq.Value);
            bll.DeletePayrollDeduction(payroll_deduction_seq, Convert.ToInt32(Session["EmpSeq"]));
            hdfPayRollDeductionSeq.Value = null;
            LoadRadGridDeductionIndex();
            UpdateUI(EditorCommand.ViewAllDeduction);
        }

        protected void ddlEmpTypeSeq_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadRadGridIndex();
            LoadLabelPayrollStatus();
        }

        protected void txbBgmYearNo_TextChanged(object sender, EventArgs e)
        {
            LoadDdlProjOper();
            LoadDdlProjOperExpense(); 
        }

        protected void txbYearNo_TextChanged(object sender, EventArgs e)
        {
            LoadRadGridIndex();
            LoadLabelPayrollStatus();
        }

        protected void RadGridIndex_ItemCommand(object sender, GridCommandEventArgs e)
        {

        }

        protected void RadGridIndex_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            LoadRadGridIndex(true);
        }

        protected void RadGridIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateUI(EditorCommand.ViewAll);
        }

        protected void ddlBgmProjOperSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDdlProjOperExpense();
        }
        
        protected void ddlExpGrpSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDdlProjOperExpense();
        }

        protected void ddlBgmProjOperExpSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            // txbTitle.Text = ddlBgmProjOperExpSeq.Text;

        }

        protected void ddlBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDdlProjOper();
            LoadDdlProjOperExpense();
            LoadDdlExpenseGroup();
        }
        
        protected void btnSentPayment_Click(object sender, EventArgs e)
        {
            if (!CheckAmount())
            {
                lblSubmitSucess.Text = "จำนวนเงินเกินจากเงินคงเหลือในอนุมัติดำเนินงาน";
                btnSend.Enabled = false;
                lblSubmitSucess.Visible = true;
                return;
            } 

            SentPayment();
            //btnCheuqNew.Visible = false;
            //btnCollect.Visible = false;
            //btnSend.Visible = false;
            

            //SendToMoneyRequest();
            //LoadLabelPayrollStatus();
            //LoadRadGridIndex();
        }

        private bool CheckAmount()
        {
            Dictionary<int, double> dic = new Dictionary<int,double>();

            foreach (GridDataItem item in dgtPayrollCombine.Items)
            {
                int BgmProjOperExpSeq = main.ConvertNullInt(main.WebString(item["bgm_proj_oper_exp_seq"].Text)) ?? 0;
                double Amount = main.ConvertNullDouble(main.WebString(item["amount"].Text)) ?? 0;

                if (!dic.ContainsKey(BgmProjOperExpSeq))
                {
                    dic.Add(BgmProjOperExpSeq, Amount);
                }
                else
                {
                    dic[BgmProjOperExpSeq] += Amount;
                }
            }

            foreach (var x in dic)
            {
                if (!poeBll.CheckAmount(x.Key, x.Value))
                {
                    return false;
                }
            }
            return true;
        }
        
        protected void btnUndoSentPayment_Click(object sender, EventArgs e)
        {
            bll.MarkAsNotSentToPayment(Convert.ToInt32(ddlMonth.SelectedValue),  Convert.ToInt32(txbYearNo.Value), Convert.ToInt32(Session["EmpSeq"]));
            LoadLabelPayrollStatus();
            LoadRadGridIndex();
        }

        protected void ddlMonth_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {

        }

        #endregion

        #region DataLoad

        private void InitialBind()
        {
            txbYearNo.Text = DateTime.Now.ToString("yyyy", new CultureInfo("th-TH"));
            LoadDdlMonth(DateTime.Now.Month);
            LoadRadGridIndex();
            LoadlblMonthYear();
        }

        private void InitialBindComplete()
        {
            LoadLabelPayrollStatus();
        }

        protected void LoadDdlEmpTypeSeq()
        {
            ddlEmpTypeSeq.DataSource = empTypeBll.GetList();
            ddlEmpTypeSeq.DataBind();
        }

        protected void LoadDdlMonth(int initialMonth)
        {
            ddlMonth.SelectedValue = initialMonth.ToString();
        }

        protected void LoadDdlSource()
        {
            ddlBgmSourceSeq.DataSource = sourceBll.GetList();
            ddlBgmSourceSeq.DataBind();
        }

        protected void LoadDdlProjOper()
        {
            ddlBgmProjOperSeq.DataSource = popBll.GetProjectListByEmpSeq(Convert.ToString(txbBgmYearNo.Value), ddlBgmSourceSeq.SelectedValue,
                                                                         Session["EmpSeq"].ToString());
            ddlBgmProjOperSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlBgmProjOperSeq);
            ddlBgmProjOperSeq.SelectedIndex = 0;
        }

        protected void LoadDdlProjOperExpense()
        {
            ddlBgmProjOperExpSeq.DataSource = !string.IsNullOrEmpty(ddlBgmProjOperSeq.SelectedValue)
                                                  ? poeBll.GetList(ddlBgmProjOperSeq.SelectedValue, ddlBgmSourceSeq.SelectedValue, ddlExpGrpSeq.SelectedValue)
                                                  : null;
            ddlBgmProjOperExpSeq.DataBind();
            if(ddlBgmProjOperExpSeq.DataSource == null)
            {
                ddlBgmProjOperExpSeq.Text = string.Empty;
                ddlBgmProjOperExpSeq.ClearSelection();
                ddlBgmProjOperExpSeq.Items.Clear();
                
            }
             

            main.InsertEmptyDDLSelect(ddlBgmProjOperExpSeq);
            ddlBgmProjOperExpSeq.SelectedIndex = 0;
        }

         protected void LoadDdlMasContact()
        {
            ddlConId.DataSource = bll.GetIcmMasContact();
            ddlConId.DataBind();

            main.InsertEmptyDDLSelect(ddlConId);
            ddlConId.SelectedIndex = 0;
        } 

        protected void LoadDdlMasContactDeduction()
        {
            ddlConIdDeduction.DataSource = bll.GetIcmMasContact();
            ddlConIdDeduction.DataBind();

            main.InsertEmptyDDLSelect(ddlConIdDeduction);
            ddlConIdDeduction.SelectedIndex = 0;
        }

        protected void LoadDdlExpenseGroup()
        {
            ddlExpGrpSeq.DataSource = expGrpBll.GetList(null); //ddlBgmSourceSeq.SelectedValue);
            ddlExpGrpSeq.DataBind();
            // เลือกงบอุดหนุนเป็นค่าเริ่มต้นสำหรับ สรพ.
            ddlExpGrpSeq.SelectedValue = "4";
        }

        protected void LoadRadGridIndex(bool dontBind = false)
        {
            var dtGetPayrolls = bll.GetPayrolls(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value));
            var dtDetails = dal.GetDetails(Convert.ToInt32(txbYearNo.Value), Convert.ToInt32(ddlMonth.SelectedValue));
            lblCountEmp.Text = dtDetails.Count.ToString("#,##0");
            RadGridIndex.DataSource = dtGetPayrolls;
            if(!dontBind) RadGridIndex.DataBind();

            // คือ Grid แท็บสรุปรายการเงินเดือนที่ต้องส่ง
            LoadGridPayrollTotal();


            LoadGridPayrollCombine();

            // Sum จำนวนเงินจาก fim_payroll
            decimal PayrollAmount = dtGetPayrolls.Sum(x => x.amount);
            
            // Sum จำนวนเงินจาก fim_payroll_deduction

            string a =  bll.SumDeduction(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value));
            

            if (a.ToString() != "")
            {
                //decimal b = (decimal)a;
                decimal total = PayrollAmount - Math.Round(main.ConvertNullDecimal(a) ?? 0,2);

                lblTotalAmount.Text = total + " บาท";

                if (total == 0)
                {
                    btnSend.Enabled = true;
                }
                else
                {
                    btnSend.Enabled = false;
                }
            }
            else
            {
                btnSend.Enabled = false;
            }
        }

        protected void LoadRadGridDeductionIndex(bool dontBind = false)
        {
            var payrollDeduction = bll.GetPayrollDeductions(Convert.ToInt32(hdfPayRollSeq.Value));
            RadGridDeductionIndex.DataSource = payrollDeduction;
            if(!dontBind) RadGridDeductionIndex.DataBind();

            var payroll = bll.GetPayrolls(Convert.ToInt32(hdfPayRollSeq.Value)).FirstOrDefault();
            lblDeductionTotalAmount.Text = payroll.deduction_total_amount.ToString("#,##0.00 บาท");
        }

        protected void LoadLabelPayrollStatus()
        {
            bool isSentToPayment = bll.CheckSentToPayment(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value));
            
            lblCurrentSalaryMonthStatus.Visible = isSentToPayment;
            btnSentPayment.Visible = !isSentToPayment;
            btnUndoSentPayment.Visible = isSentToPayment;
            cmdAddNew.Visible = !isSentToPayment; 
        }

        protected void LoadlblMonthYear(string monthStr = null, string yearStr = null)
        {
            if(string.IsNullOrEmpty(monthStr))
            {
                monthStr = ddlMonth.Text;
            } else
            {
                ddlMonth.SelectedValue = monthStr;
                monthStr = ddlMonth.Text;
            }
            if(string.IsNullOrEmpty(yearStr))
            {
                yearStr = Convert.ToString(txbYearNo.Value);
            } else
            {
                txbYearNo.Value = main.ConvertNullInt(yearStr);
            }
            lblMonthYear.Text = "เดือน " + monthStr + " พ.ศ. " + yearStr;
        }

        #endregion

        #region Transaction Database

        private bool Insert()
        {
            string modelError;
            if(!string.IsNullOrEmpty(modelError = GetModelError()))
            {
                main.MessageAlert2(Page, modelError);
                return false;
            }
            var payroll = new M_FIM_Payroll(); 
            payroll.ref_no = new B_CodeGenerate().GetNextCode(TransectionType.FimPayrollRefNo, "");
            payroll.emp_type_seq = Convert.ToInt32(ddlEmpTypeSeq.SelectedValue);
            payroll.req_date = dtpReqDate.GetDateValue().Value;

            payroll.bgm_exp_grp_seq = Convert.ToInt32(ddlExpGrpSeq.SelectedValue);
            payroll.year_no = Convert.ToInt32(hdfYearNo.Value);
            payroll.bgm_year_no = Convert.ToInt32(txbBgmYearNo.Text);
            payroll.month_no = Convert.ToInt32(ddlMonth.SelectedValue);
            payroll.title = txbTitle.Text;

            payroll.ConId = Convert.ToInt32(ddlConId.SelectedValue);
            payroll.amount = Convert.ToDecimal(txbAmount.Value);
            payroll.bgm_proj_oper_exp_seq = Convert.ToInt32(ddlBgmProjOperExpSeq.SelectedValue);

            payroll.record_status = "U";
            hdfPayRollSeq.Value = bll.InsertPayroll(payroll).ToString();
            lblPayrollTitle2.Text = lblPayrollTitle3.Text = payroll.title;
            lblRefNo.Text = payroll.ref_no;

            return true;
        }
        
        private bool Update()
        {
            string modelError;
            if(!string.IsNullOrEmpty(modelError = GetModelError()))
            {
                main.MessageAlert2(Page, modelError);
                return false;
            }
            if(main.ConvertNullInt(hdfPayRollSeq.Value) == null)
            {
                main.MessageAlert2(Page, "ไม่มีรหัสของรายการที่ต้องการแก้ไข");
                return false;
            }
            var payroll = new M_FIM_Payroll();
            payroll.payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value); 
            payroll.ref_no = Convert.ToString(lblRefNo.Text);
            payroll.emp_type_seq = Convert.ToInt32(ddlEmpTypeSeq.SelectedValue);
            payroll.req_date = dtpReqDate.GetDateValue().Value;

            payroll.bgm_exp_grp_seq = Convert.ToInt32(ddlExpGrpSeq.SelectedValue);
            payroll.year_no = Convert.ToInt32(hdfYearNo.Value);
            payroll.bgm_year_no = Convert.ToInt32(txbBgmYearNo.Value);
            payroll.month_no = Convert.ToInt32(ddlMonth.SelectedValue);
            payroll.title = txbTitle.Text;

            payroll.ConId = Convert.ToInt32(ddlConId.SelectedValue);
            payroll.amount = Convert.ToDecimal(txbAmount.Value);
            payroll.bgm_proj_oper_exp_seq = Convert.ToInt32(ddlBgmProjOperExpSeq.SelectedValue);

            payroll.record_status = "U";
            bll.UpdatePayroll(payroll);

            return true;
        }
        
        private bool InsertDeduction()
        {
            string modelError;
            if(!string.IsNullOrEmpty(modelError = GetModelErrorDeduction()))
            {
                main.MessageAlert2(Page, modelError);
                return false;
            }
            var payrollDeduction = new M_FIM_PayrollDeduction();
            payrollDeduction.payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value);
            payrollDeduction.title = Convert.ToString(txbTitleDeduction.Text);
            payrollDeduction.ConId = Convert.ToInt32(ddlConIdDeduction.SelectedValue);
            payrollDeduction.amount = Convert.ToDecimal(txbAmountDeduction.Value);
            payrollDeduction.record_status = "U";

            bll.InsertPayrollDeduction(payrollDeduction);

            return true;
        }
        
        private bool UpdateDeduction()
        {
            string modelError;
            if(!string.IsNullOrEmpty(modelError = GetModelErrorDeduction()))
            {
                main.MessageAlert2(Page, modelError);
                return false;
            }
            int? payroll_deduction_seq;
            if((payroll_deduction_seq = main.ConvertNullInt(hdfPayRollDeductionSeq.Value)) == null)
            {
                main.MessageAlert2(Page, "ไม่พบรหัสรายการที่จะปรับปรุง");
                return false;
            }
            var payrollDeduction = new M_FIM_PayrollDeduction();
            payrollDeduction.payroll_deduction_seq = payroll_deduction_seq.Value;
            payrollDeduction.payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value);
            payrollDeduction.title = Convert.ToString(txbTitleDeduction.Text);
            payrollDeduction.ConId = Convert.ToInt32(ddlConIdDeduction.SelectedValue);
            payrollDeduction.amount = Convert.ToDecimal(txbAmountDeduction.Value);
            payrollDeduction.record_status = "U";
            bll.UpdatePayrollDeduction(payrollDeduction);
            return true;
        }

        private void SendToMoneyRequest()
        {
            var datas = bll.GetPayrolls(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value));
            foreach (var data in datas)
            {
                {
                    var moneyRequest = new M_FIM_MoneyRequests();
                    // moneyRequest.money_req_seq = 0; 
                    moneyRequest.bgm_source_seq = data.BgmProjectOperationExpense.m_bgm_projectexpense.bgm_source_seq;
                    moneyRequest.bgm_year = data.bgm_year_no;
                    moneyRequest.bgm_exp_grp_seq = data.bgm_exp_grp_seq;
                    moneyRequest.work_area_seq = null;
                    moneyRequest.event_seq = 14;
                    moneyRequest.money_req_date = data.req_date;
                    moneyRequest.use_advance = "0";
                    moneyRequest.advance_bgm_source_seq = null;
                    moneyRequest.ref_no = data.ref_no;
                    //moneyRequest. doc_ref_no = 1;
                    moneyRequest.money_req_name = data.title;
                    //moneyRequest. money_req_name2 = 1;
                    //moneyRequest. money_req_name_plus = 1;
                    moneyRequest.bgm_proj_oper_seq = data.BgmProjectOperationExpense.bgm_proj_oper_seq;
                    moneyRequest.emp_seq = Convert.ToInt32(Session["EmpSeq"]);
                    moneyRequest.job_site_seq = data.BgmProjectOperationExpense != null && data.BgmProjectOperationExpense.m_bgm_project != null
                                                    ? data.BgmProjectOperationExpense.m_bgm_project.job_site_seq
                                                    : null;
                    moneyRequest.contact_seq = data.ConId;
                    //moneyRequest.icm_dn_seq = 1;
                    //moneyRequest.approver_seq = 1;
                    //moneyRequest.travel_req_seq = 1;
                    //moneyRequest.borrow_no = 1;
                    //moneyRequest.borrow_type_seq = 1;
                    //moneyRequest.borrow_start_date = 1;
                    //moneyRequest.borrow_end_date = 1;
                    //moneyRequest.borrow_return_date = 1;
                    //moneyRequest.transfer_type_seq = 1;
                    //moneyRequest.credit_card_no = 1;
                    moneyRequest.allow = "1";
                    //moneyRequest.debtor_EmpSeq = 1;
                    //moneyRequest.debtor_contact_seq = 1;
                    //moneyRequest.tran_grp_seq = 1;
                    //moneyRequest.remarks = 1;
                    //moneyRequest.transfer_job_site_seq = 1;
                    //moneyRequest.transfer_job_site_name = 1;

                    moneyRequest.approved_by = null;
                    moneyRequest.approved_when = null;
                    moneyRequest.record_status = null;
                    moneyRequest.record_status_name = null;
                    moneyRequest.created_by = Convert.ToInt32(Session["EmpSeq"]);
                    moneyRequest.created_when = DateTime.Now;
                    var money_req_seq = mrBll.Insert(moneyRequest);

                    var mrdtl = new M_FIM_MoneyRequestDtls();
                    mrdtl.money_req_seq = Convert.ToInt32(money_req_seq);
                    mrdtl.bgm_proj_oper_exp_seq = data.bgm_proj_oper_exp_seq;
                    mrdtl.amount = Convert.ToDouble(data.amount);
                    mrdBll.Insert(mrdtl);
                }
            }

            bll.MarkAsSentToPayment(Convert.ToInt32(ddlMonth.SelectedValue),  Convert.ToInt32(txbYearNo.Value), Convert.ToInt32(Session["EmpSeq"]));
        }

        #endregion

        #region UiControl

        private void UpdateUI(EditorCommand editorCommand)
        {
            PanelIndex.Visible = false;
            PanelEdit.Visible = false;
            PanelDeductionIndex.Visible = false;
            PanelDeductionEdit.Visible = false;
            PanelCommand.Visible = false;
            PanelDeductionCommand.Visible = false;

            cmdViewAll.Visible = false;
            cmdViewAll2.Visible = false;
            cmdAddNew.Visible = false;
            cmdInsert.Visible = false;
            cmdUpdate.Visible = false;
            
            cmdViewAllDeduction1.Visible = false;
            cmdViewAllDeduction2.Visible = false;
            cmdAddNewDeduction.Visible = false;
            cmdInsertDeduction.Visible = false;
            cmdUpdateDeduction.Visible = false;

            switch (editorCommand)
            {
                case EditorCommand.ViewAll:
                    PanelIndex.Visible = true;
                    PanelCommand.Visible = true;
                    cmdAddNew.Visible = true; 
                    break;
                case EditorCommand.Insert:
                    PanelEdit.Visible = true;
                    PanelCommand.Visible = true;
                    PanelDeductionIndex.Visible = true;
                    PanelDeductionCommand.Visible = true;
                    cmdViewAll2.Visible = true;
                    cmdAddNewDeduction.Visible = AllowEditData;
                    UpdateFieldForm(false,true);
                    PanelDeductionIndex.Visible = true;
                    break;
                case EditorCommand.Update:
                    PanelEdit.Visible = true;
                    PanelDeductionIndex.Visible = true;
                    PanelDeductionCommand.Visible = true;
                    PanelCommand.Visible = true;
                    UpdateFieldForm(false,true);
                    cmdViewAll2.Visible = true;
                    cmdAddNewDeduction.Visible = AllowEditData;
                    break;
                case EditorCommand.Edit:
                    PanelEdit.Visible = true;
                    PanelCommand.Visible = true;
                    cmdViewAll.Visible = true;
                    cmdUpdate.Visible = true;
                    UpdateFieldForm();
                    break;
                case EditorCommand.AddNew:
                    PanelEdit.Visible = true;
                    PanelCommand.Visible = true;
                    cmdViewAll.Visible = true;
                    cmdInsert.Visible = true;
                    UpdateFieldForm();
                    break;
                case EditorCommand.Detail:
                    PanelEdit.Visible = true;
                    PanelCommand.Visible = true;
                    cmdViewAll2.Visible = true;
                    UpdateFieldForm(false,true);
                    PanelDeductionCommand.Visible = true;
                    PanelDeductionIndex.Visible = true;
                    cmdAddNewDeduction.Visible = AllowEditData;
                    break;
                case EditorCommand.ViewAllDeduction:
                    PanelEdit.Visible = true;
                    PanelCommand.Visible = true;
                    cmdViewAll2.Visible = true;
                    UpdateFieldForm(false,true);
                    PanelDeductionCommand.Visible = true;
                    PanelDeductionIndex.Visible = true;
                    cmdAddNewDeduction.Visible = AllowEditData;
                    break;
                case EditorCommand.InsertDeduction: 
                    PanelDeductionCommand.Visible = true;
                    PanelDeductionEdit.Visible = true;
                    cmdViewAllDeduction2.Visible = true;
                    UpdateFieldFormDeduction(false,true);
                    break;
                case EditorCommand.EditDeduction:
                    UpdateFieldFormDeduction(false,true);
                    PanelDeductionCommand.Visible = true;
                    PanelDeductionEdit.Visible = true;
                    cmdViewAllDeduction1.Visible = true;
                    cmdUpdateDeduction.Visible = true;
                    UpdateFieldFormDeduction();
                    break;
                case EditorCommand.UpdateDeduction:
                    PanelDeductionEdit.Visible = true;
                    PanelDeductionCommand.Visible = true;
                    cmdViewAllDeduction2.Visible = true;
                    UpdateFieldFormDeduction(false,true);
                    cmdAddNewDeduction.Visible = AllowEditData;
                    break;
                case EditorCommand.AddNewDeduction:
                    UpdateFieldFormDeduction(false,true);
                    PanelDeductionCommand.Visible = true;
                    PanelDeductionEdit.Visible = true;
                    cmdViewAllDeduction1.Visible = true;
                    cmdInsertDeduction.Visible = true;
                    UpdateFieldFormDeduction();
                    break;
                case EditorCommand.DetailDeduction:
                    PanelDeductionEdit.Visible = true;
                    PanelDeductionCommand.Visible = true;
                    cmdViewAllDeduction2.Visible = true;
                    UpdateFieldFormDeduction(false,true);
                    cmdAddNewDeduction.Visible = AllowEditData;
                    break;
            }
        }

        private void UpdateFieldFormDeduction(bool enableEditor = true, bool enableDetail = false)
        {
            txbTitleDeduction.Visible = enableEditor;
            lblTitleDeduction.Text = txbTitleDeduction.Text;
            lblTitleDeduction.Visible = enableDetail;

            ddlConIdDeduction.Visible = enableEditor;
            lblConIdDeduction.Text = ddlConIdDeduction.Text;
            lblConIdDeduction.Visible = enableDetail;

            txbAmountDeduction.Visible = enableEditor;
            lblAmountDeduction.Text = txbAmountDeduction.Text;
            lblAmountDeduction.Visible = enableDetail;

        }

        private void UpdateFieldForm(bool enableEditor = true, bool enableDetail = false)
        {
            txbBgmYearNo.Visible = enableEditor;
            lblBgmYearNo.Text = txbBgmYearNo.Text;
            lblBgmYearNo.Visible = enableDetail;

            ddlEmpTypeSeq.Visible = enableEditor;
            lblEmpTypeSeq.Text = ddlEmpTypeSeq.Text;
            lblEmpTypeSeq.Visible = enableDetail;

            dtpReqDate.Visible = enableEditor;
            lblReqDate.Text = dtpReqDate.GetStringValue();
            lblReqDate.Visible = enableDetail;

            ddlBgmSourceSeq.Visible = enableEditor;
            lblBgmSourceSeq.Text = ddlBgmSourceSeq.Text;
            lblBgmSourceSeq.Visible = enableDetail;

            ddlExpGrpSeq.Visible = enableEditor;
            lblExpGrpSeq.Text = ddlExpGrpSeq.Text;
            lblExpGrpSeq.Visible = enableDetail;

            ddlBgmProjOperSeq.Visible = enableEditor;
            lblBgmProjOperSeq.Text = ddlBgmProjOperSeq.Text;
            lblBgmProjOperSeq.Visible = enableDetail;

            ddlBgmProjOperExpSeq.Visible = enableEditor;
            lblBgmProjOperExpSeq.Text = ddlBgmProjOperExpSeq.Text;
            lblBgmProjOperExpSeq.Visible = enableDetail;

            txbTitle.Visible = enableEditor;
            lblTitle.Text = txbTitle.Text;
            lblTitle.Visible = enableDetail;

            ddlConId.Visible = enableEditor;
            lblConId.Text = ddlConId.Text;
            lblConId.Visible = enableDetail;

            txbAmount.Visible = enableEditor;
            lblAmount.Text = (txbAmount.Value ?? 0).ToString("#,##0.00");
            lblAmount.Visible = enableDetail;

        }

        private string GetModelError()
        {
            int? payrollSeq = main.ConvertNullInt(hdfPayRollSeq.Value);
            var selectedYear = main.ConvertNullInt(hdfYearNo.Value);
            var selectedMonth = main.ConvertNullInt(hdfMonthNo.Value);
            var selecetedBgmYear = main.ConvertNullInt(txbBgmYearNo.Text);
            var selectedReqDate = dtpReqDate.GetDateValue();
            var selectedBgmSourceSeq = main.ConvertNullInt(ddlBgmSourceSeq.SelectedValue);
            var selectedEmpTypeSeq = main.ConvertNullInt(ddlEmpTypeSeq.SelectedValue);
            var selectedBgmProjOperSeq = main.ConvertNullInt(ddlBgmProjOperSeq.SelectedValue);
            var selectedBgmProjOperExpSeq = main.ConvertNullInt(ddlBgmProjOperExpSeq.SelectedValue);
            var selectedConId = main.ConvertNullInt(ddlConId.SelectedValue);
            var selectedAmount = txbAmount.Value;

            if(selectedYear == null || selectedMonth == null)
            {
                return "ปีหรือเดือนที่เลือกสำหรับการทำรายการ";
            }
            if(selecetedBgmYear == null)
            {
                return "ปีงบประมาณ";
            }
            if(selectedReqDate == null)
            {
                return "วันที่ต้องการใช้";
            }
            if(selectedBgmSourceSeq == null)
            {
                return "แหล่งเงิน";
            }
            if(selectedEmpTypeSeq == null)
            {
                return "ประเภทบุคลากร";
            }
            if(selectedBgmProjOperSeq == null)
            {
                return "โครงการ";
            }
            if(selectedBgmProjOperExpSeq == null)
            {
                return "ค่าใช้จ่าย";
            }
            if (selectedConId == null)
            {
                return "ผู้รับเงิน";
            }
            if(!selectedAmount.HasValue || selectedAmount <= 0)
            {
                return "จำนวนเงิน";
            }

            var payrolls = bll.GetPayrolls();

            if (!poeBll.CheckAmount(selectedBgmProjOperExpSeq ?? -1, selectedAmount ?? 0))
            {
                return "จำนวนเงินสุทธิ มากกว่าจำนวนเงินคงเหลือในโครงการ";
            //                         (poeSelected.amount ?? 0).ToString("#,##0.00"));
            }
            //M_BGM_ProjectOperationExpense poeSelected = poeBll.GetList(Convert.ToString(selectedBgmProjOperSeq), 
            //    Convert.ToString(selectedBgmSourceSeq), null).First();

            //if(poeSelected.remain_amount != null && poeSelected.remain_amount < txbAmount.Value)
            //{
            //    return string.Format("จำนวนเงินสุทธิ ({0} บาท)มากกว่าจำนวนเงินคงเหลือในโครงการ ({1} บาท)", txbAmount.Value.Value.ToString("#,##0.00"),
            //                         (poeSelected.remain_amount ?? 0).ToString("#,##0.00"));
            //}
            //if(poeSelected.amount == null || poeSelected.amount < txbAmount.Value)
            //{
            //    return string.Format("จำนวนเงินสุทธิ ({0} บาท)มากกว่าจำนวนเงินในโครงการ ({1} บาท)", txbAmount.Value.Value.ToString("#,##0.00"),
            //                         (poeSelected.amount ?? 0).ToString("#,##0.00"));
            //}
            
            if(payrollSeq.HasValue)
            {
                payrolls = payrolls.Where(o => o.payroll_seq != payrollSeq).ToList();
            }

            payrolls = payrolls.Where(o => o.year_no == selectedYear && o.month_no == selectedMonth).ToList();
            payrolls = payrolls.Where(o => o.bgm_proj_oper_exp_seq == selectedBgmProjOperExpSeq).ToList();
            payrolls = payrolls.Where(o => o.ConId == selectedConId).ToList();

            //if(payrolls.Count > 0)
            //{
            //    return string.Format("มีรายการที่ใช้ค่าใช้จ่ายและผู้รับเงินเดียวกันกับรายการที่กำลังบันทึก");
            //}
            return null;
        }
        
        private string GetModelErrorDeduction()
        {
            if(main.ConvertNullInt(hdfPayRollSeq.Value)  == null)
            {
                return "Payroll PK";
            }
            if(string.IsNullOrEmpty(txbTitleDeduction.Text))
            {
                return "ชื่อรายการ";
            }
            if(main.ConvertNullInt(ddlConIdDeduction.SelectedValue)  == null)
            {
                return "ผู้รับเงิน";
            }
            if(!txbAmountDeduction.Value.HasValue || txbAmountDeduction.Value <= 0)
            {
                return "จำนวนเงิน";
            }

            return null;

        }

        protected void ClearControl()
        {
            lblRefNo.Text = "Auto Generate";
            lblMonthYear.Text = null;
            txbBgmYearNo.Value = null;
            main.ClearDDL(ddlEmpTypeSeq);
            dtpReqDate.SetValue(DateTime.Now);

            //main.ClearDDL(ddlBgmSourceSeq);
            //main.ClearDDL(ddlExpGrpSeq);
            main.ClearDDL(ddlBgmProjOperSeq);
            main.ClearDDL(ddlBgmProjOperExpSeq);
            txbTitle.Text = null;
            main.ClearDDL(ddlConId);
            txbAmount.Value = null;
        }

        protected void ClearControlDeduction()
        {
            txbTitleDeduction.Text = null;
            lblTitleDeduction.Text = null;
            main.ClearDDL(ddlConIdDeduction);
            lblConIdDeduction.Text = null;
            txbAmountDeduction.Value = null;
            lblAmountDeduction.Text = null;
        }
        
        private void LoadEditor()
        {
            var payroll_seq = Convert.ToInt32(hdfPayRollSeq.Value);
            var payroll = bll.GetPayrolls(payroll_seq).First();
            
            if(payroll == null) throw new NoNullAllowedException("Can't load pay roll");

            lblRefNo.Text = payroll.ref_no;
            LoadlblMonthYear(Convert.ToString(payroll.month_no), Convert.ToString(payroll.year_no));
            txbBgmYearNo.Value = payroll.bgm_year_no;
            hdfYearNo.Value = payroll.year_no.ToString();
            hdfMonthNo.Value = payroll.month_no.ToString();
            LoadDdlEmpTypeSeq();
            ddlEmpTypeSeq.SelectedValue = Convert.ToString(payroll.emp_type_seq);
            dtpReqDate.SetValue(payroll.req_date);
            LoadDdlSource();
            if (payroll.BgmProjectOperationExpense != null &&
                payroll.BgmProjectOperationExpense.m_bgm_projectexpense != null &&
                payroll.BgmProjectOperationExpense.m_bgm_projectexpense.bgm_source_seq != null)
            {
                ddlBgmSourceSeq.SelectedValue = payroll.BgmProjectOperationExpense.m_bgm_projectexpense.bgm_source_seq.Value.ToString();
            }
            LoadDdlExpenseGroup();
            if (payroll.bgm_exp_grp_seq > 0)
            {
                ddlExpGrpSeq.SelectedValue = Convert.ToString(payroll.bgm_exp_grp_seq);
            }
            LoadDdlProjOper();
            var firstProjOper = poeBll.GetList(null, null, null).FirstOrDefault(o => o.bgm_proj_oper_exp_seq == payroll.bgm_proj_oper_exp_seq);
            ddlBgmProjOperSeq.SelectedValue = Convert.ToString(firstProjOper != null ? firstProjOper.bgm_proj_oper_seq : null);
            LoadDdlProjOperExpense();
            ddlBgmProjOperExpSeq.SelectedValue = Convert.ToString(payroll.bgm_proj_oper_exp_seq);
            lblPayrollTitle3.Text = lblPayrollTitle2.Text = txbTitle.Text = Convert.ToString(payroll.title);
            LoadDdlMasContact();
            ddlConId.SelectedValue = Convert.ToString(payroll.ConId);
            txbAmount.Value = Convert.ToDouble(payroll.amount);
        }
        
        private void LoadEditorDeduction()
        {
            var payroll_deduction_seq = Convert.ToInt32(hdfPayRollDeductionSeq.Value);
            var payroll_deduction = bll.GetPayrollDeductions(null, payroll_deduction_seq).First();
            
            if(payroll_deduction == null) throw new NoNullAllowedException("Can't load pay roll deduction");
            
            txbTitleDeduction.Text = payroll_deduction.title;
            LoadDdlMasContactDeduction();
            ddlConIdDeduction.SelectedValue = Convert.ToString(payroll_deduction.ConId);
            txbAmountDeduction.Value = main.ConvertNullDouble(payroll_deduction.amount);
        }

        public bool AllowEditData
        {
            get { return !bll.CheckSentToPayment(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value)); }
        }

        protected void btnCollect_Click(object sender, EventArgs e)
        {
            
            int flag = (main.ConvertNullInt(bll.RunningNumber()) ?? 0) + 1;
            int flagSentpayment = 1;
            int count = RadGridPayrollTotal.Items.Count;
            
            List<M_FIM_Payroll_Sentpayment> models = new List<M_FIM_Payroll_Sentpayment>();

            if (RadGridPayrollTotal.Items != null)
            {
                
                foreach (GridDataItem item in RadGridPayrollTotal.SelectedItems)
                {
                    M_FIM_Payroll_Sentpayment model = new M_FIM_Payroll_Sentpayment();

                    model.payroll_seq = main.ConvertNullInt(main.WebString(item["payroll_seq"].Text));
                    model.payroll_deduction_seq = main.ConvertNullInt(main.WebString(item["payroll_deduction_seq"].Text));
                    model.ConId = main.ConvertNullInt(main.WebString(item["ConId"].Text)) ?? 0;
                    model.payroll_sentpayment_name = main.WebString(item["DeductionTitle"].Text); //bll.PaymentGroupName(flag);
                    model.amount =  Convert.ToDecimal(main.WebString(item["Total"].Text));
                    model.payroll_sentpayment_combine = flag;
                    model.created_by = creatby.EmpSeqI;
                    model.month_no = Convert.ToInt32(ddlMonth.SelectedValue);
                    model.year_no = Convert.ToInt32(txbYearNo.Value);
                    //model.amount = main.ConvertNullDecimal(bll.SumAmount(flag)) ?? 0;
                    bll.InsertSentpayment(model);
                    bll.UpdateFlagSentpayment(model.payroll_deduction_seq, flagSentpayment);

                    ///LoadCheuq
                    string bgmSeq = (main.WebString(item["bgm_source_seq"].Text));
                    ///
                    models.Add(model);
                }

                List<M_FIM_Payroll_Sentpayment> dtPayrollCombine = models;

                int j = 0;
                foreach (var list in models)
                {
                    int i = models.Count();
                  
                    List<M_FIM_Payroll_Sentpayment_Combine> payroll = new List<M_FIM_Payroll_Sentpayment_Combine>();
                    list.payroll_sentpayment_name = bll.PaymentGroupName(flag);
                    list.amount = bll.SumAmount(flag);
                    list.created_by = creatby.EmpSeqI;
                    list.month_no = Convert.ToInt32(ddlMonth.SelectedValue);
                    list.year_no = Convert.ToInt32(txbYearNo.Value);
                    Convert.ToInt32(list.payroll_seq);
                    Convert.ToInt32(list.payroll_deduction_seq);
                    Convert.ToInt32(list.ConId);

                    int ChequeSeq = Convert.ToInt32(ddlChequeSeq.SelectedValue);

                    j  = j + 1;

                    if (j == i)
                    {
                        bll.InsertSentpaymentCombine(Convert.ToInt32(list.ConId), list.payroll_sentpayment_name, list.amount, list.created_by
                                                    , list.month_no, list.year_no, Convert.ToInt32(list.payroll_seq), ChequeSeq);
                        btnSend.Enabled = true;
                    }
                }

                foreach(var i in models)
                {
                    Convert.ToInt32(i.payroll_seq);
                    Convert.ToInt32(i.payroll_deduction_seq);
                    bll.sentpaymentCombineSeq(Convert.ToInt32(i.payroll_deduction_seq), Convert.ToInt32(i.payroll_seq));
                }


                LoadGridPayrollTotal();
                LoadGridPayrollCombine();
            }
        }

        protected void btnCheuqNew_Click(object sender, EventArgs e)
        {
            List<M_FIM_Payroll_Sentpayment> models = new List<M_FIM_Payroll_Sentpayment>();
            int flagSentpayment = 0;

            int mounth = Convert.ToInt32(ddlMonth.SelectedValue);
            int year = Convert.ToInt32(txbYearNo.Value); ;
            DataTable checklist = ChecklistPayrollDeduction(mounth, year);

            foreach (DataRow list in checklist.Rows)
            {
                int Seq = Convert.ToInt32(list["payroll_deduction_seq"]);
                bll.UpdateFlagSentpayment(Seq, flagSentpayment);
            }

            List<M_FIM_Payroll_Sentpayment_Combine> model = new List<M_FIM_Payroll_Sentpayment_Combine>();
            if (dgtPayrollCombine.Items != null)
            {
                foreach (GridDataItem item in dgtPayrollCombine.Items)
                {
                    M_FIM_Payroll_Sentpayment_Combine listCombine = new M_FIM_Payroll_Sentpayment_Combine();

                    listCombine.payroll_sentpayment_combine_seq = main.ConvertNullInt(main.WebString(item["payroll_sentpayment_combine_seq"].Text)) ?? 0;
                    listCombine.pay_seq = main.ConvertNullInt(main.WebString(item["pay_seq"].Text)) ?? 0;

                    int Seq = listCombine.payroll_sentpayment_combine_seq;
                    int PaySeq = listCombine.pay_seq;

                    bll.DeleteSentpayment(Seq, PaySeq);
                    bll.DeletePayment(PaySeq);
                    bll.DeleteMoneyReq(PaySeq);
                    bll.DeleteMoneyDtlReq(PaySeq);
                    bll.DeleteSentpaymentComb(mounth, year);
                }
            }
            LoadGridPayrollCombine();
            LoadGridPayrollTotal();

        }

        public DataTable ChecklistPayrollDeduction(int intMonth, int intYear)
        {
            DataTable dt = new DataTable();
            string strSQL;

            try
            {
                dbManager.Open();
                dbManager.CreateParameters(3);
                dbManager.AddParameters(0, "@month", intMonth);
                dbManager.AddParameters(1, "@year", intYear);
                dbManager.AddParameters(2, "@record_status", SystemInfo._DeleteRecordStatus);

                strSQL = @"SELECT pd.payroll_deduction_seq FROM fim_payroll p 
                        LEFT JOIN fim_payroll_deduction pd ON pd.payroll_seq = p.payroll_seq
                        WHERE pd.record_status <> @record_status  AND p.record_status <> @record_status AND p.month_no = @month AND year_no = @year";


            dt = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];


            }
            catch (Exception ex)
            {

                throw (ex);
            }
            finally
            {
                dbManager.Dispose();
            }

            return dt;
        }
        
        private void LoadGridPayrollCombine()
        {
            DataTable dtPayrollCombine = bll.GridPayrollCombine(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value));
            dgtPayrollCombine.DataSource = dtPayrollCombine;
            dgtPayrollCombine.DataBind();
        }

        private void LoadGridPayrollTotal()
        {
            DataTable dtPayrollTotal = bll.PayrollTotal(Convert.ToInt32(ddlMonth.SelectedValue), Convert.ToInt32(txbYearNo.Value));
            RadGridPayrollTotal.DataSource = dtPayrollTotal;
            RadGridPayrollTotal.DataBind();
        }

        protected void LoadDDLBankAccSeq()
        {
            ddlBankAccSeq.DataSource = acc.GetList("2", ddlBgmSourceSeq.SelectedValue, null, null);
            ddlBankAccSeq.DataBind();

            ddlBankAccSeq.SelectedIndex = 0;
            LoadDDLChequeSeq();
        }

        protected void LoadDDLChequeSeq()
        {
            ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, null, null, "1");
            ddlChequeSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlChequeSeq);
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected void ddlBankAccSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLChequeSeq();
        }

        private void SentPayment()
        {
            List<M_FIM_Payroll_Sentpayment_Combine> models = new List<M_FIM_Payroll_Sentpayment_Combine>();

            if (dgtPayrollCombine.Items != null)
            {
                foreach (GridDataItem item in dgtPayrollCombine.Items)
                {
                    string strPaySeq = main.WebString(item["pay_seq"].Text);

                    if (strPaySeq.Length == 0)
                    {
                        M_FIM_Payroll_Sentpayment_Combine model = new M_FIM_Payroll_Sentpayment_Combine();

                        model.payroll_sentpayment_combine_seq = main.ConvertNullInt(main.WebString(item["payroll_sentpayment_combine_seq"].Text)) ?? 0;
                        model.ConId = main.ConvertNullInt(main.WebString(item["ConId"].Text)) ?? 0;
                        model.amount = Convert.ToDecimal(main.WebString(item["amount"].Text));
                        model.payroll_sentpayment_combine_name = main.WebString(item["payroll_sentpayment_combine_name"].Text);
                        model.month_no = Convert.ToInt32(ddlMonth.SelectedValue);
                        model.year_no = Convert.ToInt32(txbYearNo.Value);
                        model.pay_seq = main.ConvertNullInt(main.WebString(item["pay_seq"].Text)) ?? 0;
                        model.cheque_seq = Convert.ToInt32(main.WebString(item["cheque_seq"].Text));

                        models.Add(model);

                        M_FIM_Payments info = new M_FIM_Payments();

                        int nBgmSourceSeq = main.ConvertNullInt(main.WebString(item["bgm_source_seq"].Text)) ?? 0;
                        int nBgmExpGrpSeq = main.ConvertNullInt(main.WebString(item["bgm_exp_grp_seq"].Text)) ?? 0;
                        int nBgmProjOperSeq = main.ConvertNullInt(main.WebString(item["bgm_proj_oper_seq"].Text)) ?? 0;
                        int nBgmProjOperExpSeq = main.ConvertNullInt(main.WebString(item["bgm_proj_oper_exp_seq"].Text)) ?? 0;
                        string strBgmYear = bll.BgmyearToPayment(model.payroll_sentpayment_combine_seq);
                        int nContactSeq = model.ConId;
                        int nEventSeq = (nContactSeq == 4424 ? 28 : 14);//hardcode ถ้าเป็น สรรพากร ให้เป็นการนำส่ง ภงด. 1
                        string strPayName = "จ่ายเงินเดือน " + model.month_no + " ปี " + model.year_no + " " + model.payroll_sentpayment_combine_name;
                        string strMrRefNo = cg.GetNextCode(TransectionType.FimMoneyRequestRefNo, nBgmSourceSeq == 1 ? "1" : "2");
                        string strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, nBgmSourceSeq == 1 ? "1" : "2");
                        //nt strMoneyReqSeq = Convert.ToInt32(money_req_seq);
                        int nEmpSeq = creatby.EmpSeqI;
                        double dAmount = main.ConvertNullDouble(model.amount) ?? 0;
                        double dVatPercent = 0;
                        double dTaxPercent = 0;
                        double dVatAmount = 0;
                        double dTaxAmount = 0;
                        int nMethodSeq = 2;
                        string strUserID = Session["EmpSeq"].ToString();

                        /////////////////// Insert MoneyRequests ////////////////////////
                        var mr = new M_FIM_MoneyRequests();
                        mr.ref_no = strMrRefNo;
                        mr.bgm_exp_grp_seq = null;
                        mr.bgm_source_seq = nBgmSourceSeq;
                        mr.bgm_exp_grp_seq = nBgmExpGrpSeq;
                        mr.bgm_proj_oper_seq = nBgmProjOperSeq;
                        mr.record_status = "A";
                        mr.work_area_seq = 0;
                        mr.emp_seq = nEmpSeq;
                        mr.contact_seq = nContactSeq;
                        mr.bgm_year = main.ConvertNullInt(strBgmYear);
                        mr.event_seq = nEventSeq;
                        mr.money_req_name = strPayName;
                        mr.money_req_date = DateTime.Today;
                        mr.use_advance = "0";
                        mr.allow = "1";
                        mr.record_status = "W";
                        mr.created_by = nEmpSeq;
                        mr.created_when = DateTime.Now;
                        int nMoneyReqSeq = Convert.ToInt32(mrBll.Insert(mr));

                        /////////////////// Insert MoneyRequestsDtls ////////////////////////
                        var mrdtl = new M_FIM_MoneyRequestDtls();
                        mrdtl.money_req_seq = nMoneyReqSeq;
                        mrdtl.bgm_proj_oper_exp_seq = nBgmProjOperExpSeq;
                        mrdtl.percent_vat = 0;
                        mrdtl.percent_tax = 0;
                        mrdtl.amount = dAmount;
                        mrdtl.record_status = "W";
                        mrdtl.created_by = creatby.EmpSeqI;
                        mrdtl.created_when = DateTime.Now;
                        mrdBll.Insert(mrdtl);

                        mr.money_req_seq = nMoneyReqSeq;
                        mr.record_status = "A";
                        mr.updated_by = creatby.EmpSeqI;
                        mr.updated_when = DateTime.Now;
                        mrBll.ChangeStatus(mr);

                        /////////////////// Insert Payment ////////////////////////
                        info.bgm_source_seq = nBgmSourceSeq;
                        info.work_area_seq = 0; //Convert.ToInt32(string.IsNullOrEmpty(strWorkAreaSeq) ? "0" : strWorkAreaSeq);
                        info.bgm_year = Convert.ToInt32(strBgmYear);
                        info.event_seq = nEventSeq;
                        info.pay_name = strPayName;
                        info.ref_no = strRefNo;
                        info.pay_date = DateTime.Today;
                        info.money_req_seq = nMoneyReqSeq;
                        info.emp_seq = nEmpSeq;
                        info.contact_seq = nContactSeq;
                        info.amount = dAmount;
                        info.vat_rate = dVatPercent;
                        info.tax_rate = dTaxPercent;
                        info.vat = dVatAmount;
                        info.tax = dTaxAmount;
                        info.method_seq = nMethodSeq;
                        info.created_by = creatby.EmpSeqI;
                        info.created_when = DateTime.Now;
                        info.record_status = "W";

                        payment.Insert(info);
                        bll.UpdatePayseqToCombine(model.payroll_sentpayment_combine_seq); //นำ last id ของ pay_seq ไป upadate เพื่อให้สามารถอ้างถึงกัน
                        bll.InsertCheques(model.pay_seq, model.cheque_seq, model.amount, creatby.EmpSeqI); //Insert Cheques
                    }
                    else
                    {
                        lblSubmitSucess.Text = "ส่งไปการเงินแล้ว ไม่สามารถส่งซ้ำได้อีก";
                        lblSubmitSucess.Visible = true;
                        btnSend.Enabled = false;

                        //return;
                    }
                }
            }

            btnSend.Enabled = false;
            lblSubmitSucess.Text = "ส่งข้อมูลไปที่การเงินเรียบร้อย";
            lblSubmitSucess.Visible = true;

            LoadGridPayrollCombine();
        }

        protected void RadGridPayrollTotal_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Sort" || e.CommandName == "Filter" || e.CommandName == "RebindGrid")
            {
                LoadGridPayrollTotal();
            }
        }

        protected void RadGridDeductionIndex_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Sort" || e.CommandName == "Filter" || e.CommandName == "RebindGrid")
            {
                LoadRadGridDeductionIndex();
            }
        }

        protected void dgtPayrollCombine_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Sort" || e.CommandName == "Filter" || e.CommandName == "RebindGrid")
            {
                LoadGridPayrollCombine();
            }
        }

        //protected void btnPrint_Click(object sender, EventArgs e)
        //{
        //    var payroll = bll.GetPayrolls();
        //}

        //public string moneyReqLastSeq()
        //{
        //    string strSQL;
        //    string LastSeq;

        //    try
        //    {
        //        dbManager.Open();
        //        dbManager.CreateParameters(1);
        //        dbManager.AddParameters(0, "@record_status", SystemInfo._DeleteRecordStatus);

        //        strSQL = "(SELECT MAX(money_req_seq) as lastSeq FROM fim_money_requests WHERE record_status <> 'D')";


        //        DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

        //        LastSeq = Convert.ToString(dtb.Rows[0][0]);
        //        return LastSeq;
        //    }
        //    catch (Exception ex)
        //    {

        //        throw (ex);
        //    }
        //    finally
        //    {
        //        dbManager.Dispose();
        //    }
        //}

        #endregion 
    }
}